package com.yq.cp.utils.wx;


import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.RandomStringUtils;

import javax.servlet.http.HttpServletRequest;
import java.net.InetAddress;
import java.net.UnknownHostException;

public class CommonUtil {
    /**
     * 雪花算法id生成
     */
    private static final SnowFlake SNOW_FLAKE = new SnowFlake(0, 0);

    /**
     * 生成指定位数的随机数字字符串
     *
     * @return {@link String}
     */
    public static String generateRandomNumeric(int length) {
        return RandomStringUtils.randomNumeric(length);
    }

    /**
     * 生成指定位数的随机字符串
     *
     * @return {@link String}
     */
    public static String generateRandomString(int length) {
        return RandomStringUtils.randomAlphanumeric(length);
    }

    /**
     * 生成订单号
     *
     * @return {@link String}
     */
    public static String generateOrderId() {
        return String.valueOf(SNOW_FLAKE.nextId());
    }

    /**
     * 生成新文件名
     *
     * @param filename 原文件名
     * @return {@link String}
     */
    public static String generateNewFilename(String filename) {
        String prefix = CommonUtil.generateRandomString(50);
        String suffix = FilenameUtils.getExtension(filename);
        return prefix + "." + suffix;
    }

    /**
     * 获取请求IP
     *
     * @param request request
     * @return {@link String}
     */
    public static String getIpAddress(HttpServletRequest request) {
        String ipAddress;
        try {
            ipAddress = request.getHeader("x-forwarded-for");
            if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
                ipAddress = request.getHeader("Proxy-Client-IP");
            }
            if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
                ipAddress = request.getHeader("WL-Proxy-Client-IP");
            }
            if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
                ipAddress = request.getRemoteAddr();
                if ("127.0.0.1".equals(ipAddress) || "0:0:0:0:0:0:0:1".equals(ipAddress)) {
                    InetAddress inetAddress = null;
                    try {
                        inetAddress = InetAddress.getLocalHost();
                    } catch (UnknownHostException e) {
                        e.printStackTrace();
                    }
                    if (inetAddress != null) {
                        ipAddress = inetAddress.getHostAddress();
                    }
                }
            }
            if (ipAddress != null) {
                if (ipAddress.contains(",")) {
                    ipAddress = ipAddress.split(",")[0];
                }
            }
        } catch (Exception e) {
            ipAddress = "";
        }
        return ipAddress;
    }
}
